package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.exception.LogicException;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.mapper.PermissionMapper;
import cn.wolfcode.service.EmployeeService;
import cn.wolfcode.qo.EmployeeQueryObject;
import cn.wolfcode.utils.PasswordUtil;
import cn.wolfcode.utils.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * 员工业务层
 *
 * @author 杨兴健
 * @Date 2020/7/8 9:32
 */
@Service

public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper mapper;

    @Autowired
    private PermissionMapper permissionMapper;

    /**
     * 根据条件查询员工信息并封装为ResultSet对象
     *
     * @param qo
     * @return
     */
    @Override
    public PageInfo<Employee> selectAllByQO(EmployeeQueryObject qo) {

//        用pageHelper插件开始分页
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Employee> employees = mapper.selectAllByQO(qo);
//     用PageHelper插件封装结果集
        PageInfo<Employee> pageInfo = new PageInfo<>(employees);

        return pageInfo;
    }

    /**
     * 根据id删除员工
     *
     * @param id
     */
    @Override
    public void delete(Long id) {
        mapper.delete(id);
    }

    /**
     * 根据id查询员工
     *
     * @param id
     * @return
     */
    @Override
    public Employee selectById(Long id) {
        return mapper.selectById(id);
    }


    /**
     * 更新员工信息
     *
     * @param employee
     */
    @Override
    public void update(Employee employee) {
        mapper.update(employee);
    }

    /**
     * 添加员工
     *
     * @param employee
     */
    @Override
    public void insert(Employee employee) {
        mapper.insert(employee);
    }

    /**
     * 添加员工与角色的关联关系
     *
     * @param eid
     * @param rid
     */
    @Override
    public void insertRelation(Long eid, Long rid) {
        mapper.insertRelation(eid, rid);
    }

    /**
     * 删除员工与角色的关联关系
     *
     * @param eid
     */
    @Override
    public void deleteRelation(Long eid) {
        mapper.deleteRelation(eid);
    }


    /**
     * 获取表达式
     *
     * @param eid
     * @return
     */
    @Override
    public List<String> getExpressions(Long eid) {
        return permissionMapper.selectByEid(eid);
    }


    /**
     * 更新密码
     *
     * @param oldPassword
     * @param newPassword
     */
    @Override
    public void updatePwd(String oldPassword, String newPassword) {
        Employee employee = UserContext.getCurrentUser();

        if (!employee.getPassword().equals(oldPassword)) {
            throw new RuntimeException("原密码错误，请重新输入");
        }
        //给密码加密加盐
        PasswordUtil.setMD5HashPassword(employee);
        mapper.updatePwd(employee.getId(), employee.getPassword());
    }

    /**
     * 新增或更新用户
     *
     * @param employee
     * @param rids
     */
    @Override
    public void saveOrUpdate(Employee employee, Long[] rids) {
        if (employee == null) {
            throw new RuntimeException("没有数据");
        }

        if (employee.getId() != null) {
            mapper.deleteRelation(employee.getId());
            mapper.update(employee);
        } else {
            //给密码加密加盐
            PasswordUtil.setMD5HashPassword(employee);
            mapper.insert(employee);
        }
        if (rids != null && rids.length > 0) {
            for (Long rid : rids) {
                mapper.insertRelation(employee.getId(), rid);
            }
        }
    }

    /**
     * 改变用户状态
     *
     * @param id
     */
    @Override
    public void changeStatus(Long id) {
        mapper.updateStatus(id);
    }


    /**
     * 检查用户名是否存在
     *
     * @param id
     * @param name
     * @return
     */
    @Override
    public boolean checkName(Long id, String name) {
        //根据姓名查询用户
        Employee employee = mapper.selectByName(name);
        return employee == null || employee.getId().equals(id);

    }

    /**
     * 批量删除用户
     *
     * @param ids
     */
    @Override
    public void batchDelete(Long[] ids) {
        if (ids == null || ids.length < 1) {
            throw new RuntimeException("没有选择要删除的用户");
        }
        mapper.batchDelete(ids);
    }

    /**
     * 批量导入
     *
     * @param file
     */
    @Override
    public void importXls(MultipartFile file) throws IOException {
        //从字节流中生成excel文件
        HSSFWorkbook sheets = new HSSFWorkbook(file.getInputStream());
        //读第0张表
        HSSFSheet sheet = sheets.getSheetAt(0);
        //创建员工对象
        Employee employee = new Employee();

        //获取最后一行的索引
        int lastRowNum = sheet.getLastRowNum();
        //获取每一行的数据
        for (int i = 1; i <= lastRowNum; i++) {
            HSSFRow row = sheet.getRow(i);
            employee.setName(row.getCell(0).getStringCellValue());
            HSSFCell cell = row.getCell(1);
            CellType cellType = cell.getCellType();
            if (cellType == CellType.NUMERIC) {
                employee.setAge((int) cell.getNumericCellValue());
            } else {
                employee.setAge(Integer.valueOf(row.getCell(1).getStringCellValue()));
            }
            employee.setEmail(row.getCell(2).getStringCellValue());
            mapper.insert(employee);
        }
    }

    /**
     * 批量导出
     *
     * @return
     */
    @Override
    public HSSFWorkbook exportXls() {
        //创建excel文档
        HSSFWorkbook sheets = new HSSFWorkbook();
        //创建excel表
        HSSFSheet sheet = sheets.createSheet("员工信息表");
        //查询出所有的用户信息
        List<Employee> employees = mapper.selectAll();
        //创建行
        HSSFRow row = sheet.createRow(0);
        //创建单元格并写数据
        row.createCell(0).setCellValue("用户id");
        row.createCell(1).setCellValue("姓名");
        row.createCell(2).setCellValue("年龄");
        row.createCell(3).setCellValue("email");
        //循环遍历所有用户,并写入单元格
        for (int i = 1; i <= employees.size(); i++) {
            Employee employee = employees.get(i - 1);
            HSSFRow row1 = sheet.createRow(i);
            row1.createCell(0).setCellValue(employee.getId());
            row1.createCell(1).setCellValue(employee.getName());
            row1.createCell(2).setCellValue(employee.getAge());
            row1.createCell(3).setCellValue(employee.getEmail());
        }
        return sheets;
    }

    /**
     * 重置密码
     *
     * @param id
     * @param newPassword
     */
    @Override
    public void resetPwd(Long id, String newPassword) {
        Employee employee = mapper.selectById(id);
        PasswordUtil.setMD5HashPassword(employee, newPassword);
        mapper.updatePwd(id, employee.getPassword());
    }

    /**
     * 查询所有员工
     *
     * @return
     */
    @Override
    public List<Employee> selectAll() {
        return mapper.selectAll();
    }

    /**
     * 根据角色编码查询员工
     *
     * @param sns
     * @return
     */
    @Override
    public List<Employee> selectByRoleSn(String... sns) {
        return mapper.selectByRoleSn(sns);
    }
}
